package com.lhframework.upload.controller;

import com.lhframework.upload.uploader.FileUploader;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by lh on 2017/8/8.
 */
@RestController
public class DownloadController {
    @Autowired
    private FileUploader fileUploader;

    @ApiOperation(value = "下载文件")
    @RequestMapping(value = "/download/{fileName:.+}", method = RequestMethod.GET)
    public void download(@PathVariable String fileName, HttpServletResponse response) {
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            IOUtils.copy(fileUploader.download(fileName), os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
